/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.allscore.batch.test.handler;

import com.allscore.batch.test.entity.Product;
import javax.persistence.EntityManagerFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.database.JpaPagingItemReader;
import org.springframework.batch.item.database.orm.JpaNativeQueryProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 *
 * @author Administrator
 */
@Component
// 需要参数的话，需要@StepScope注解来获取JobLauncher.run传递的参数
@StepScope
public class ProductJPAPageReader extends JpaPagingItemReader<Product> {

    private static final int PAGE_SIZE = 5;

    private static String QUERY_SQL = "select * from product";

    public ProductJPAPageReader(EntityManagerFactory entityManagerFactory,
            @Value("#{jobParameters['id']}") long id) throws Exception {

        JpaNativeQueryProvider<Product> queryProvider = new JpaNativeQueryProvider<>();

        queryProvider.setSqlQuery(QUERY_SQL + " where id >= " +  id );

        queryProvider.setEntityClass(Product.class);

        try {
            queryProvider.afterPropertiesSet();
        } catch (Exception e) {
            throw e;
        }

        this.setEntityManagerFactory(entityManagerFactory);

        this.setPageSize(PAGE_SIZE);

        this.setQueryProvider(queryProvider);

        this.afterPropertiesSet();

        this.setSaveState(true);
    }
}
